<template>
  <div class="main">
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="loginRef"
      :model="loginState"
    >
      <a-form-item>
      <a-input
      size="large" 
      placeholder="请输入账号"
      v-model:value="loginState.phone" >
        <template #prefix>
          <user-outlined type="user" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input-password
      size="large" 
      v-model:value="loginState.passwd"
      placeholder="请输入密码"
      >
      <template #prefix>
        <lock-outlined type="lock" />
      </template>
      </a-input-password>
    </a-form-item>

    <a-form-item style="margin-top:48px">
      <a-button size="large" class="login-button" type="primary"
        @click="handleLogin"
       :loading="loading"
       :disabled="loading">登 录</a-button>
    </a-form-item>
    </a-form>
  </div>
</template>
<script>
import { reactive, ref } from "vue";
import { validatorName, validatorPassword } from "@/utils/validator";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";

export default {
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const loginRef = ref();
    const loading = ref(false);
    const loginState = reactive({
      phone: "",
      passwd: "",
      tenantId: "1"
    });
    const rules = {
      phone: [{ required: true, trigger: "blur", validator: validatorName }],
      passwd: [
        { required: true, trigger: "blur", validator: validatorPassword }
      ]
    };
    const handleLogin = () => {
      loginRef.value
        .validate()
        .then(() => {
          loading.value = true;
          store
            .dispatch("user/login", loginState)
            .then(() => {
              loading.value = false;
              router.push({ path: route.query.redirect || "/" });
            })
            .catch((err) => {
               console.log("error", err);
              loading.value = false;
            });
        })
        .catch(err => {
          console.log("error", err);
        });
    };
    const resetForm = () => {
      loginRef.value.resetFields();
    };
    return {
      loginRef,
      loading,
      loginState,
      rules,
      handleLogin,
      resetForm
    };
  }
};
</script>

<style>
.main {
  min-width: 260px;
  width: 368px;
  margin: 0 auto;
}
.login-button {
  padding: 0 15px;
  font-size: 16px;
  height: 40px;
  width: 100%;
}
</style>